
<?php
// <editor-fold defaultstate="collapsed" desc="variabler">

/**
 * Override content width (for photo and video embeds)
 */
$content_width = 500;
$hide_right_sidebar = false;
$valgt_aktivitet = 0;
$aktivitet_side = 'plan';
$valgt_medlem = 0;
$medlem_side = 'liste';
$valgt_nyhet = 0;
$nyhet_side = 'hjem';
$valgt_mottaker = 0;

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="metodekall">

/**
 * Fjerner admin bar på toppen av websiden.
 */
show_admin_bar(false);

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="overskrivende metoder">
// <editor-fold defaultstate="collapsed" desc="mytheme_widgets_init()">

/**
 * Register extra sidebar
 */
function mytheme_widgets_init() {
    register_sidebar(array(
        'name' => __('Left Sidebar', 'tto'),
        'id' => 'sidebar-4',
        'description' => __('The Left Sidebar. Displayed on all but full width and homepage template.', 'mytheme'),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => "</aside>",
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}

add_action('widgets_init', 'mytheme_widgets_init');

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="mytheme_content_width()">

/**
 * 
 * Display 1000px width content if full width page template
 */
function mytheme_content_width() {
    if (is_page_template('page-templates/full-width.php') || is_attachment()) {
        global $content_width;
        $content_width = 1000;
    }
}

add_action('template_redirect', 'mytheme_content_width', 11);

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="mytheme_twentytwelvw_setup()">

/**
 * Change default thumbnail size
 */
function mytheme_twentytwelve_setup() {
    set_post_thumbnail_size(500, 9999); // (default featured images)Unlimited height, soft crop
}

add_action('after_setup_theme', 'mytheme_twentytwelve_setup', 11);

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="mytheme_body_class()">

/**
 * 
 * Add child theme body class
 */
function mytheme_body_class($classes) {

    if (!is_page_template())
        $classes[] = 'custom-layout';

    return $classes;
}

add_filter('body_class', 'mytheme_body_class');

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="twentytwelve_entry_meta()">

/**
 * 
 */
function twentytwelve_entry_meta() {
// Translators: used between list items, there is a space after the comma.
    $categories_list = get_the_category_list(__(', ', 'twentytwelve_child'));

// Translators: used between list items, there is a space after the comma.
    $tag_list = get_the_tag_list('', __(', ', 'twentytwelve_child'));

    $date = sprintf('<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a>', esc_url(get_permalink()), esc_attr(get_the_time()), esc_attr(get_the_date('c')), esc_html(get_the_date())
    );

    $author = sprintf('<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>', esc_url(get_author_posts_url(get_the_author_meta('ID'))), esc_attr(sprintf(__('View all posts by %s', 'twentytwelve_child'), get_the_author())), get_the_author()
    );

// Translators: 1 is category, 2 is tag, 3 is the date and 4 is the author's name.
    if ($tag_list)
        $utility_text = __('Denne nyheten er lagt til som %1$s og tagget %2$s den %3$s<span class="by-author"> av %4$s</span>.', 'twentytwelve_child');
    elseif ($categories_list)
        $utility_text = __('Denne nyheten er lagt til som %1$s den %3$s<span class="by-author"> av %4$s</span>.', 'twentytwelve_child');
    else
        $utility_text = __('Denne nyheten er lagt til som %3$s<span class="by-author"> av %4$s</span>.', 'twentytwelve_child');

    printf(
            $utility_text, $categories_list, $tag_list, $date, $author
    );
}

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="twentytwelve_child_theme_page_menu_args()">

/**
 * Makes our wp_nav_menu() fallback -- wp_page_menu() -- show a home link.
 * 
 * Endret til å sette "Hjem" istedenfor "Home".
 * 
 */
function twentytwelve_child_theme_page_menu_args($args) {
    if (!isset($args['show_home']))
        $args['show_home'] = "Hjem";
    return $args;
}

add_filter('wp_page_menu_args', 'twentytwelve_child_theme_page_menu_args');

// </editor-fold>
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="egendefinerte metoder">

function ham_aktivitetsdager($loggedin, $output_format = ARRAY_A) {
    global $wpdb;

    $offentlig = "";
    if (!$loggedin)
        $offentlig = " WHERE offentlig = 1";

    return $wpdb->get_results("
        SELECT DISTINCT DAYOFMONTH(fradato) AS dag, MONTH(fradato) AS mnd, DAYOFWEEK(fradato) AS ukedag, fradato
        FROM arrangement"
                    . $offentlig
                    . " ORDER BY fradato ASC", $output_format);
}

function ham_dagens_aktiviteter($dato, $loggedin = false, $output_format = ARRAY_A) {
    global $wpdb;

    $offentlig = "";
    if (!$loggedin) {
        $offentlig = " AND offentlig = 1";
    }

    return $wpdb->get_results("
        SELECT HOUR(fratid) AS time, MINUTE(fratid) AS min, arrangement AS arr, arrangementid AS aID
        FROM arrangement
        WHERE fradato = '$dato'"
                    . $offentlig
                    . " ORDER BY fratid ASC", $output_format);
}

function ham_lag_sql_dato($dag, $mnd, $år) {
    return $år . '-' . zeroise($mnd, 2) . '-' . zeroise($dag, 2);
}

function ham_getdate() {
    global $ham_chosendate;
    return $ham_chosendate;
}

function ham_setdate($year, $month, $day = 1) {
    global $ham_chosendate;
    $ham_chosendate = $year . '-' . zeroise($month, 2) . '-' . zeroise($day, 2);
}

function ham_maketime($hour, $minute) {
    $ham_time = zeroise(intval($hour), 2);
    $ham_time .= ':';
    $ham_time .= zeroise(intval($minute), 2);
    return $ham_time;
}

/**
 * Sender en melding fra $sid til $mid med innholdet $mldinnhold
 * @global type $wpdb
 * @param type $sid Sender id
 * @param type $mid Mottaker id
 * @param type $mldinnhold Meldingsinnhold
 */
function ham_sendmelding($sid, $mid, $mldinnhold) {
    global $wpdb;
    $mlddata = array(
        'senderid' => $sid,
        'mottakerid' => $mid,
        'innhold' => $mldinnhold
    );
    $wpdb->insert('meldinger', $mlddata);
}

// <editor-fold defaultstate="collapsed" desc="jquery metoder">

/**
 * laster inn wordpress sin jquery og muligjør bruk av ajax og jquery
 * og viser til vår js fil
 */
function your_function_name() {
    wp_enqueue_script('ajax_impl', get_stylesheet_directory_uri() . '/js/ajax-implementation.js', 'jquery', true);
    wp_localize_script('ajax_impl', 'my_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
}

add_action('template_redirect', 'your_function_name');

/**
 * lister meldingene for den valgte brukeren
 * @global type $current_user
 * @global type $wpdb
 * @global type $valgt_mottaker
 */

function liste_meldinger() {

    global $current_user, $wpdb, $valgt_mottaker;
    $valgt_mottaker = $_POST['mottaid'];
    $mottaker = get_user_by('id', $valgt_mottaker);
    $curUserId = get_current_user_id();
    $meldingliste =
            $wpdb->get_results("
        SELECT c.inn AS innh, mottakerid, datom
FROM
(
    SELECT innhold AS inn, datom, mottakerid
    FROM meldinger
    WHERE mottakerid = '$curUserId' and senderid = '$valgt_mottaker'
    
    UNION
    
    SELECT innhold AS inn, datom, mottakerid
    FROM meldinger
    WHERE senderid = '$curUserId' and mottakerid = '$valgt_mottaker'
) AS c
ORDER BY datom ASC", ARRAY_A);
    $sendinfo = "<p>Liste over meldinger mellom deg og $mottaker->first_name $mottaker->last_name.</p>
            <div id='meldinglisten1' style='overflow-y: auto;max-height:400px'>";
    foreach ($meldingliste as $meldinger):
        $melding = $meldinger['innh'];
        $datomo = $meldinger['datom'];
        if ($meldinger['mottakerid'] == $curUserId) {
            $sendinfo .= $datomo . ' - ' . $mottaker->first_name . ' ' . $mottaker->last_name . ' sa:';
        } else {
            $sendinfo .= $datomo . ' - ' . $current_user->first_name . ' ' . $current_user->last_name . ' sa:';
        }
        $sendinfo .= "<div style='border:1px solid #dedede'><p>";
        $sendinfo .= $melding;
        $sendinfo .= "</p></div><br/>";
    endforeach;
    $sendinfo .= '</div>
    
    <div>
        <form name="sendersvarform" id="sendersvarform" onsubmit="js_svar_melding();" >
            Skriv ny melding til ' . $mottaker->first_name . ' :<br/>
            <textarea name="meldinginnhold" id="meldinginnhold" rows="3" cols="20"></textarea> <br/>
            <input type="hidden" name="idmot" id="idmot" value="' . $valgt_mottaker . '" />
                <input  type="submit" name="submit" id="svarmelding" value="Send Svar"/>
        </form>
    </div>';

    echo $sendinfo;
    die();
}

add_action("wp_ajax_nopriv_liste_meldinger", "liste_meldinger");
add_action("wp_ajax_liste_meldinger", "liste_meldinger");

/**
 * brukt i automatisk oppdatering av meldingliste
 * @global type $current_user
 * @global type $wpdb
 * @global type $valgt_mottaker
 */
function oppdater_meldingliste() {
    global $current_user, $wpdb, $valgt_mottaker;
    $valgt_mottaker = $_POST['mottaid'];
    $mottaker = get_user_by('id', $valgt_mottaker);
    $curUserId = get_current_user_id();
    $meldingliste =
            $wpdb->get_results("
        SELECT c.inn AS innh, mottakerid, datom
FROM
(
    SELECT innhold AS inn, datom, mottakerid
    FROM meldinger
    WHERE mottakerid = '$curUserId' and senderid = '$valgt_mottaker'
    
    UNION
    
    SELECT innhold AS inn, datom, mottakerid
    FROM meldinger
    WHERE senderid = '$curUserId' and mottakerid = '$valgt_mottaker'
) AS c
ORDER BY datom ASC", ARRAY_A);
    $sendinfo = '';
    foreach ($meldingliste as $meldinger):

        $melding = $meldinger['innh'];
        $datomo = $meldinger['datom'];
        if ($meldinger['mottakerid'] == $curUserId) {
            $sendinfo .= $datomo . ' - ' . $mottaker->first_name . ' ' . $mottaker->last_name . ' sa:';
        } else {
            $sendinfo .= $datomo . ' - ' . $current_user->first_name . ' ' . $current_user->last_name . ' sa:';
        }


        $sendinfo .= "<div style='border:1px solid #dedede'><p>";
        $sendinfo .= $melding;
        $sendinfo .= "</p>
        </div>
        <br/>";
    endforeach;


    echo $sendinfo;
    die();
}

add_action("wp_ajax_nopriv_oppdater_meldingliste", "oppdater_meldingliste");
add_action("wp_ajax_oppdater_meldingliste", "oppdater_meldingliste");

/**
 * 
 */
function ny_melding_side() {
    $sendinfo = '
        Fornavn: <input  type="text"  name="mottakerfornavn" id="mottakerfornavn"/><br/>
        Etternavn: <input type="text"  name="mottakeretternavn" id="mottakeretternavn"/><br/>
        Innhold: <textarea name="meldinginnhold" id="meldinginnhold" rows="3" cols="20"></textarea> <br/>
        <input  type="submit" name="sendermelding" id="sendermelding" value="Send melding"/>
    ';


    echo $sendinfo;
    die();
}

add_action("wp_ajax_nopriv_ny_melding_side", "ny_melding_side");
add_action("wp_ajax_ny_melding_side", "ny_melding_side");

/**
 * sender meldingen som er laget i ny melding siden
 * @global type $current_user
 */
function send_melding() {
    global $current_user;
    $userID = $current_user->ID;
    if (!empty($_POST['mottakerfornavn']) && !empty($_POST['mottakeretternavn']) && !empty($_POST['meldinginnhold'])) {
        $bruker = get_users(array('meta_value' => $_POST["mottakeretternavn"]));
        foreach ($bruker as $tmpb) {
            if ($tmpb->first_name == $_POST["mottakerfornavn"]) {
                $brukeride = $tmpb->id;
            }
        }
        $sid = $userID;
        $mid = $brukeride;
        $mldinnhold = $_POST["meldinginnhold"];

        ham_sendmelding($sid, $mid, $mldinnhold);
        echo "melding sendt.";
    } else {
        echo "Ikke alle feltene er fylt inn.";
    }
    die();
}

add_action("wp_ajax_nopriv_send_melding", "send_melding");
add_action("wp_ajax_send_melding", "send_melding");

/**
 * sender meldingen som er laget i svar boksa
 * @global type $current_user
 */
    function svar_melding() {
        global $current_user;
        $userID = $current_user->ID;
        if (!empty($_POST['idmot']) && !empty($_POST['meldinginnhold'])) {
            $sid = $userID;
            $mid = $_POST['idmot'];
            $mldinnhold = $_POST['meldinginnhold'];

            ham_sendmelding($sid, $mid, $mldinnhold);
            echo $mid;
        } else {
            echo "Ikke alle feltene er fylt inn.";
        }
        die();
    }

add_action("wp_ajax_nopriv_svar_melding", "svar_melding");
add_action("wp_ajax_svar_melding", "svar_melding");


// </editor-fold>

/**
 * Sjekker om en bruker er logget inn
 * 
 * @return true hvis en bruker er logget inn
 */
function loggedin() {
    return is_user_logged_in();
}

/**
 * Sjekker om en bruker er administrator
 * 
 * @return true hvis innlogget bruker er administrator
 */
function isadmin() {
    return current_user_can('administrator') || current_user_can('superadmin');
}

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="aktivitetskalender-widget">
// <editor-fold defaultstate="collapsed" desc="widget-klassen">

class ActivitySidebarWidget extends WP_Widget {

    function ActivitySidebarWidget() {
        parent::WP_Widget(false, 'Activity Widget');
    }

    function form($instance) {
        ?>
        <h3>Ingen instillinger er nødvendig!</h3>
        <?php
    }

    function update($new_instance, $old_instance) {
        return $new_instance;
    }

    function widget($args, $instance) {
        ham_calendar(loggedin());
        ham_activity(loggedin());
        if (loggedin())
            ham_bursdag();
    }

}

register_widget('ActivitySidebarWidget');

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="widget-variabler">

$ham_chosendate = gmdate('Y-m-d H:i:s');
$week_begins = intval(get_option('start_of_week'));

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="widget-metoder">

/**
 * Kalendermodul til widgeten "Activity Calendar"
 * 
 * @param type $loggedin
 * @param type $initial
 * @param type $k_output
 * @return string
 */
function ham_calendar($loggedin = false, $initial = true) {
    global $wpdb, $m, $monthnum, $year, $wp_locale;
    global $ham_chosendate, $week_begins;

    $a_o = "";
    $w_o = "";
    if (!$loggedin) {
        $a_o = " AND offentlig = 1";
        $w_o = " WHERE offentlig = 1";
    }

    if (isset($_GET['w']))
        $w = '' . intval($_GET['w']);

    if (!empty($monthnum) && !empty($year)) {
        $thismonth = '' . zeroise(intval($monthnum), 2);
        $thisyear = '' . intval($year);
    } elseif (!empty($w)) {
        $thisyear = '' . intval(substr($m, 0, 4));
        $d = (($w - 1) * 7) + 6;
        $thismonth = $wpdb->get_var("SELECT DATE_FORMAT((DATE_ADD('${thisyear}0101', INTERVAL $d DAY)), '%m')");
    } elseif (!empty($m)) {
        $thisyear = '' . intval(substr($m, 0, 4));
        if (strlen($m) < 6)
            $thismonth = '01';
        else
            $thismonth = '' . zeroise(intval(substr($m, 4, 2)), 2);
    } else {
        $thisyear = gmdate('Y', current_time('timestamp'));
        $thismonth = gmdate('m', current_time('timestamp'));
    }

    $unixmonth = mktime(0, 0, 0, $thismonth, 1, $thisyear);

    $previous = $wpdb->get_row("
SELECT MONTH(dato) AS month, YEAR(dato) AS year
FROM arrangement
WHERE dato < '$thisyear-$thismonth-01'"
            . $a_o
            . " ORDER BY dato DESC
LIMIT 1");
    $next = $wpdb->get_row("
SELECT MONTH(dato) AS month, YEAR(dato) AS year
FROM arrangement
WHERE dato > '$thisyear-$thismonth-01'
AND MONTH(dato) != MONTH('$thisyear-$thismonth-01')"
            . $a_o
            . " ORDER BY dato ASC
LIMIT 1");

    $calendar_caption = _x('%1$s %2$s', 'calendar caption');
    ?>
    <div class="ham-modul">
        <table id="ham-kalender">
            <caption class="ham-modul-tittel"><?php echo sprintf($calendar_caption, $wp_locale->get_month($thismonth), date('Y', $unixmonth)); ?></caption>
            <thead>
                <tr>
                    <?php
                    $myweek = array();

                    for ($wdcount = 0; $wdcount <= 6; $wdcount++) {
                        $myweek[] = $wp_locale->get_weekday(($wdcount + $week_begins) % 7);
                    }

                    foreach ($myweek as $wd) {
                        $day_name = (true == $initial) ? $wp_locale->get_weekday_initial($wd) : $wp_locale->get_weekday_abbrev($wd);
                        $wd = esc_attr($wd);
                        ?>
                        <th scope="col" title="<?php echo $wd
                ?>"><?php echo $day_name ?></th>
                        <?php }
                        ?>
                </tr>
            </thead>

            <tfoot>
                <tr>
                    <?php if ($previous) { ?>
                        <td colspan="3" id="prev">
                            <a type="action" action="<?php echo ham_setdate($previous->year, $previous->month, $previous->day) ?>" title="<?php echo sprintf(__('Se aktiviteter i %1$s %2$s'), $wp_locale->get_month($previous->month), date('Y', mktime(0, 0, 0, $previous->month, 1, $previous->year))); ?>">&laquo;<?php echo ' ' . $wp_locale->get_month_abbrev($wp_locale->get_month($previous->month)); ?></a>
                        </td>
                    <?php } else {
                        ?>
                        <td colspan="3" id="prev" class="pad">&nbsp;</td>
                    <?php }
                    ?>

                    <td>&nbsp;</td>
                    <?php if ($next) { ?>
                        <td colspan="3" id="next">
                            <a href="<?php echo get_month_link($next->year, $next->month) ?>" title="<?php echo esc_attr(sprintf(__('Se aktiviteter i %1$s %2$s'), $wp_locale->get_month($next->month), date('Y', mktime(0, 0, 0, $next->month, 1, $next->year)))) ?>"><?php echo $wp_locale->get_month_abbrev($wp_locale->get_month($next->month)) ?> &raquo;</a>
                        </td>
                    <?php } else {
                        ?>
                        <td colspan="3" id="next" class="pad">&nbsp;</td>
                    <?php }
                    ?>
                </tr>
            </tfoot>

            <tbody>
                <tr>
                    <?php
                    $dayswithposts = $wpdb->get_results("
    SELECT DISTINCT DAYOFMONTH(dato)
    FROM arrangement
    WHERE MONTH(dato) = '$thismonth'
    AND YEAR(dato) = '$thisyear'"
                            . $a_o, ARRAY_N);
                    if ($dayswithposts) {
                        foreach ((array) $dayswithposts as $daywith) {
                            $daywithpost[] = $daywith[0];
                        }
                    } else {
                        $daywithpost = array();
                    }

                    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'camino') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) {
                        $ak_title_separator = "\n";
                    } else {
                        $ak_title_separator = ', ';
                    }

                    $ak_titles_for_day = array();
                    $ak_post_titles = $wpdb->get_results("
    SELECT arrangementid, arrangement, DAYOFMONTH(dato) as dom
    FROM arrangement
    WHERE YEAR(dato) = '$thisyear'
    AND MONTH(dato) = '$thismonth'"
                            . $a_o
                    );
                    if ($ak_post_titles) {
                        foreach ((array) $ak_post_titles as $$ak_post_title) {
                            $post_title = esc_attr(apply_filters('the_title', $ak_post_title->arrangement, $ak_post_title->arrangementid));

                            if (empty($ak_titles_for_day['day_' . $ak_post_title->dom]))
                                $ak_titles_for_day['day_' . $ak_post_title->dom] = '';
                            if (empty($ak_titles_for_day["$ak_post_title->dom"]))
                                $ak_titles_for_day["$ak_post_title->dom"] = $post_title;
                            else
                                $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title;
                        }
                    }

                    $pad = calendar_week_mod(date('w', $unixmonth) - $week_begins);
                    if (0 != $pad) :
                        ?>
                        <td colspan="<?php echo esc_attr($pad) ?>" class="pad"> &nbsp;</td>
                        <?php
                    endif;
                    $daysinmonth = intval(date('t', $unixmonth));
                    for ($day = 1; $day <= $daysinmonth; ++$day) {
                        if (isset($newrow) && $newrow) {
                            ?>
                        </tr>
                        <tr>
                            <?php
                        }
                        $newrow = false;

                        if ($day == gmdate('j', current_time('timestamp')) && $thismonth == gmdate('m', current_time('timestamp')) && $thisyear == gmdate('Y', current_time('timestamp'))) {
                            if (in_array($day, $daywithpost)) {
                                ?>
                                <td id="today"><a href="<?php echo get_day_link($thisyear, $thismonth, $day) ?>" title="<?php echo esc_attr($ak_titles_for_day[$day]) ?>"> <?php echo $day ?></a></td>
                            <?php } else {
                                ?>
                                <td id="today"><?php echo $day ?></td>
                                <?php
                            }
                        } else {
                            if (in_array($day, $daywithpost)) {
                                ?>
                                <td><a href="<?php echo get_day_link($thisyear, $thismonth, $day) ?>" title="<?php echo esc_attr($ak_titles_for_day[$day]) ?>"> <?php echo $day ?></a></td>
                            <?php } else {
                                ?>
                                <td><?php echo $day ?></td>
                                <?php
                            }
                        }
                        if (6 == calendar_week_mod(date('w', mktime(0, 0, 0, $thismonth, $day, $thisyear)) - $week_begins)) {
                            $newrow = true;
                        }
                    }

                    $pad = 7 - calendar_week_mod(date('w', mktime(0, 0, 0, $thismonth, $day, $thisyear)) - $week_begins);
                    if ($pad != 0 && $pad != 7) {
                        ?>
                        <td class="pad" colspan="<?php echo esc_attr($pad) ?>">&nbsp;</td>
                    <?php }
                    ?>
                </tr>
            </tbody>
        </table>
    </div>
    <?php
}

/**
 * Aktivitetslistemodul til widgeten "Activity Calendar"
 * 
 * @param type $loggedin
 */
function ham_activity($loggedin = false) {
    global $wpdb, $ham_chosendate, $wp_locale, $week_begins;

    $a_o = "";
    $w_o = "";
    if (!$loggedin) {
        $a_o = " AND offentlig = 1";
        $w_o = " WHERE offentlig = 1";
    }

    $datoer = ham_aktivitetsdager($loggedin);
    ?>
    <div class="ham-modul">
        <h1 class="ham-modul-tittel">Aktiviteter</h1>
        <div style="height:300px;overflow-y: scroll;">
            <table id="ham-modul-aktivitet-tabell">
                <tbody class="ham-modul-tabell">
                    <?php
                    foreach ($datoer as $dato) {
                        $aktiviteter = ham_dagens_aktiviteter($dato['fradato'], $loggedin);
                        ?>
                        <tr class="ham-modul-tabell-rad">
                            <td class="ham-modul-dato">
                                <h3 class="ham-modul-dato-tittel">
                                    <div class="ham-modul-dato-mnd"><?php echo $wp_locale->get_month_abbrev($wp_locale->get_month($dato['mnd'])) ?></div>
                                    <div class="ham-modul-dato-dag<?php echo $dato['ukedag'] - $week_begins == 0 ? '-søn' : '' ?>"><?php echo $dato['dag'] ?></div>
                                    <div class="ham-modul-dato-udg"><?php echo $wp_locale->get_weekday_abbrev($wp_locale->get_weekday($dato['ukedag'] - $week_begins)) ?></div>
                                </h3>
                            </td>
                            <td class="ham-modul-liste-kolonne">
                                <ol class="ham-modul-liste">
                                    <?php
                                    foreach ($aktiviteter as $aktivitet) {
                                        $skriv = (($aktivitet['time'] != null || $aktivitet['min'] != null) ? ham_maketime($aktivitet['time'], $aktivitet['min']) . ' ' : '') . $aktivitet['arr']
                                        ?>
                                        <li class="ham-modul-liste-rad">
                                            <form method="post" action="?page_id=4">
                                                <input name="action" type="hidden" value="Vis aktivitet"/>
                                                <input name="id-value" type="hidden" value="<?php echo $aktivitet['aID'] ?>"/>
                                                <input class="ham-modul-liste-tekst" type="submit" value="<?php echo $skriv ?>"/>
                                            </form>
                                        </li>
                                    <?php }
                                    ?>
                                </ol>
                            </td>
                        </tr>
                    <?php }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php
}

function ham_parsedate($datestring, $useyear = false) {
    if ($useyear)
        $year = intval(date('Y'));
    else
        $year = substr($datestring, 0, 4);
    $month = substr($datestring, 5, 2);
    $day = substr($datestring, 8);
    return mktime(0, 0, 0, $month, $day, $year);
}

/**
 * Bursdagslistemodul til widgeten "Activity Calendar"
 * 
 * @param type $loggedin
 */
function ham_bursdag() {
    global $wpdb, $ham_chosendate, $wp_locale, $week_begins;

    $datoer = $wpdb->get_results("
        SELECT DISTINCT meta_value AS dato, SUBSTRING(meta_value, 9, 2) AS dag, SUBSTRING(meta_value, 6, 2) AS mnd, SUBSTRING(meta_value, 1, 4) AS år
        FROM $wpdb->usermeta
        WHERE meta_key = 'fødselsdag'
        ORDER BY mnd ASC, dag ASC", ARRAY_A);
    ?>
    <div class="ham-modul">
        <h1 class="ham-modul-tittel">Bursdager</h1>
        <div style="height:300px;overflow-y: scroll;">
            <table id="ham-modul-bursdag-tabell">
                <tbody class="ham-modul-tabell">
                    <?php
//    for ($i = 0; $i < 2; $i++) {
                    foreach ($datoer as $dato) {
                        $d = mktime(0, 0, 0, intval($dato['mnd']), intval($dato['dag']));
                        $wd = date('w', $d);
                        ?>
                        <tr class="ham-modul-tabell-rad">
                            <td class="ham-modul-dato">
                                <h3 class="ham-modul-dato-tittel">
                                    <div class="ham-modul-dato-mnd"><?php echo $wp_locale->get_month_abbrev($wp_locale->get_month($dato['mnd'])) ?></div>
                                    <div class="ham-modul-dato-dag<?php echo $wd == 0 ? '-søn' : '' ?>"><?php echo intval($dato['dag']) ?></div>
                                    <div class="ham-modul-dato-udg"><?php echo $wp_locale->get_weekday_abbrev($wp_locale->get_weekday($wd)) ?></div>
                                </h3>
                            </td>
                            <td class="ham-modul-liste-kolonne">
                                <ol class="ham-modul-liste">
                                    <?php
                                    $personIDer = $wpdb->get_results("
            SELECT user_id AS id
            FROM $wpdb->usermeta
            WHERE meta_key = 'fødselsdag'
            AND meta_value = '" . $dato['dato'] . "'", ARRAY_A);
                                    $år = $dato['år'];
                                    foreach ($personIDer as $personID) {
                                        $pid = $personID['id'];
                                        $alder = intval(date('Y')) - intval($år);
                                        if (intval(date('n')) < intval($dato['mnd']) || (intval(date('n')) == intval($dato['mnd']) && intval(date('j')) < intval($dato['dag'])))
                                            $alder -= 1;
                                        $skriv = get_the_author_meta('first_name', $pid) . ' ' . get_the_author_meta('last_name', $pid) . "\n$år - $alder år"
                                        ?>
                                        <li class="ham-modul-liste-rad">
                                            <form method="post" action="/?page_id=10">
                                                <input name="action" type="hidden" value="Vis profil"/>
                                                <input name="idnum" type="hidden" value="<?php echo $pid ?>"/>
                                                <input class="ham-modul-liste-tekst" type="submit" value="<?php echo $skriv ?>"/>
                                            </form>
                                            <!--                                <a class="ham-modul-liste-tekst">
                                                                                <div><span><?php // echo the_author_meta('first_name', $pid)    ?></span> <span><?php // the_author_meta('last_name', $pid)    ?></span></div>
                                                                                <div><span><?php // echo $år . ' - ' . $alder     ?></span> <span><?php // echo 'år';     ?></span></div>
                                                                            </a>-->
                                        </li>
                                    <?php }
                                    ?>
                                </ol>
                            </td>
                        </tr>
                    <?php }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php
}

// </editor-fold>
// </editor-fold>

/* Setter redirect etter utlogging til forsiden av websiden, istedenfor login skjerm 
 * Hentet fra: http://projectivemotion.com/2011/07/27/wordpress-always-redirect-to-homepage-after-logout/
 */
add_filter('logout_url', 'projectivemotion_logout_home', 10, 2);

function projectivemotion_logout_home($logouturl, $redir) {
    $redir = get_option('siteurl');
    return $logouturl . '&amp;redirect_to=' . urlencode($redir);
}

//add_filter( 'get_edit_post_link', 'my_edit_post_link' );
//function my_edit_post_link( $url, $post->ID, $context) {
//    $url = f; //However you want to generate your link
//
//    return $url;
//}
?>
